'use strict'

const sha1 = require('sha1') // 加密模块
const Wechat = require('./wechat')
const getRawBody = require('raw-body')
const util = require('./util')

module.exports =  function (opts, handler) {
  let wechat = new Wechat(opts)

  return function *(next) {
    let that = this
    const token = opts.token
    const {
      signature,
      nonce,
      timestamp,
      echostr
    } = this.query
  
    const str = [token, timestamp, nonce].sort().join('') // 字典排序
    const sha = sha1(str) // 加密
    if (this.method === 'GET') {
      if (sha === signature) {
        this.body = echostr + ''
      } else {
        this.body = 'wrong'
      }
    } else if (this.method === 'POST') {
      if (sha !== signature) {
        this.body = 'wrong'

        return false
      }
      let data = yield getRawBody(this.req, {
        length: this.length,
        limit: '1mb',
        encoding: this.charset
      })
      let content = yield util.parseXMLAsync(data)
      let message = util.formatMessage(content.xml)
      this.weixin = message
      yield handler.call(this, next)
      wechat.reply.call(this)
    }
  }
}
